"""
处理图片
"""
import oss2
import os
import qrcode
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from django.utils.six import BytesIO
from finance_c2c.local_settings import Config
from finance_c2c.settings import OssAccessKey, OssAccessSecret


class EditPicture(object):
    @classmethod
    def make_dir(cls, path):
        if not os.path.exists(path):
            os.makedirs(path)

    @classmethod
    def save_file(cls, content, file_name, relation_path=""):
        """
        保存 BytesIO 文件
        :param content:
        :param relation_path:
        :param file_name:
        :return:
        """
        absolute_path = os.path.join(Config.base_dir, 'c2c_media', relation_path)
        cls.make_dir(absolute_path)
        file_path = os.path.join(absolute_path, file_name)
        content.save(file_path)
        return file_path

    @classmethod
    def past_img(cls, background_img, top_img, save_path, box=(500, 500)):
        """
        贴图片
        :param background_img: 背景图路径，或者 BytesIO
        :param top_img: 需要黏贴的图 ，或者 BytesIO
        :param save_path: 保存的位置
        :param box: 坐标
        :return:
        """
        bottom_img = Image.open(background_img)
        cover_file = Image.open(top_img)
        layer = Image.new('RGBA', bottom_img.size, (0, 0, 0, 0))
        layer.paste(cover_file, box)
        bottom_img = Image.composite(layer, bottom_img, layer)
        bottom_img.save(save_path)

    @classmethod
    def write_words(cls, file_path, lines, quality=80, save_pth=None):
        """
        :param file_path:
        :param lines: 写文字 {font_file:"绝对路径", font_size: 字号, box:(x,y), words:"文字",  "color":(0,0,0)}
        :param quality:
        :param save_pth:
        :return:
        """
        if save_pth:
            pass
        else:
            save_pth = file_path
        im = Image.open(file_path)  # 或者 BytesIO
        draw = ImageDraw.Draw(im)
        for i in lines:
            font_file = i.get("font_file")
            font_size = i.get("font_size")
            box = i.get("box")
            words = i.get("words")
            font = ImageFont.truetype(font_file, font_size)
            draw.text(box, words, i.get("color"), font=font)
        im.save(save_pth, quality=quality)

    @classmethod
    def resize_img(cls, file_path, box=(100, 100)):
        im = Image.open(file_path)
        out = im.resize(box, Image.ANTIALIAS)
        return out

    @classmethod
    def write_words_return(cls, im, lines):
        """
        写文字 {im:"Image.open(xx)", font_size: 字号, box:(x,y), words:"文字",  "color":(0,0,0) rgb}
        :return:
        """
        draw = ImageDraw.Draw(im)
        for i in lines:
            font_file = i.get("font_file")
            font_size = i.get("font_size")
            box = i.get("box")
            words = i.get("words")
            font = ImageFont.truetype(font_file, font_size)
            draw.text(box, words, i.get("color"), font=font)
        buf = BytesIO()  # 创建一个BytesIO临时保存生成图片数据
        im.save(buf, 'png')
        return im, buf

    @classmethod
    def open_rb_to_img(cls, file_path):
        """
        :param file_path:
        :return: Image 操作， BytesIO对象
        """
        file_ = open(file_path, 'rb+')  # 二进制打开
        file_stream = file_.read()  # 读
        file_buf = BytesIO(file_stream)  # 在内存中读写二进制
        file_img = Image.open(file_buf)  # Image 操作
        return file_img, file_buf

    @classmethod
    def make_qr_code(cls, url):
        """
        :return: 二进制字节，BytesIO对象
        """
        img = qrcode.make(url)  # 传入网站计算出二维码图片字节数据
        buf = BytesIO()  # 创建一个BytesIO临时保存生成图片数据
        img.save(buf)  # 将图片字节数据放到BytesIO临时保存
        image_stream = buf.getvalue()
        return image_stream, buf

    @classmethod
    def resize_img_by_bytes(cls, buf, box=(100, 100)):
        """
        :param buf: BytesIO 对象
        :param box:
        :return:
        """
        im = Image.open(buf)
        out = im.resize(box, Image.ANTIALIAS)
        new_buf = BytesIO()  # 创建一个BytesIO临时保存生成图片数据
        out.save(new_buf, 'png')
        return out, new_buf

    @classmethod
    def past_logo_by_bytes(cls, background_img, logo_img):
        """
        贴图片
        :param background_img: 背景图路径，或者 BytesIO
        :param logo_img: 需要黏贴的图 ，或者 BytesIO
        :param box: 坐标
        :return:
        """
        bottom_img = Image.open(background_img)
        logo = Image.open(logo_img)
        layer = Image.new('RGBA', bottom_img.size, (0, 0, 0, 0))
        logo_w, logo_h = logo.size
        w, h = bottom_img.size
        l_w = int((w - logo_w) / 2)
        l_h = int((h - logo_h) / 2)
        layer.paste(logo, (l_w, l_h))
        bottom_img = Image.composite(layer, bottom_img, layer)
        buf = BytesIO()  # 创建一个BytesIO临时保存生成图片数据
        bottom_img.save(buf, 'png')
        return buf

    @classmethod
    def past_img_by_bytes(cls, background_img, top_img, box=(500, 500)):
        """
        贴图片
        :param background_img: 背景图路径，或者 BytesIO
        :param top_img: 需要黏贴的图 ，或者 BytesIO
        :param box: 坐标
        :return:
        """
        bottom_img = Image.open(background_img)
        cover_file = Image.open(top_img)
        layer = Image.new('RGBA', bottom_img.size, (0, 0, 0, 0))
        layer.paste(cover_file, box)
        bottom_img = Image.composite(layer, bottom_img, layer)
        buf = BytesIO()  # 创建一个BytesIO临时保存生成图片数据
        bottom_img.save(buf, 'png')
        return buf, bottom_img

    @classmethod
    def oss_upload_bytes(cls, buf, host, bucket_name, file_name):
        """
        :param buf: bytes 对象
        :param host: 域名 http://oss-cn-beijing.aliyuncs.com
        :param bucket_name:
        :param file_name: 文件路径文件名 shop/popular.test.jpg
        :return:
        """
        auth = oss2.Auth(OssAccessKey, OssAccessSecret)
        bucket = oss2.Bucket(auth, host, bucket_name)
        bucket.put_object(file_name, buf.getvalue())
